<!--  表格组件 -->
<template>
    <div class="table-normal" :style="{ minHeight: height + 'px' }">
        <table
                data-id="bsTable"
                data-show-jump-to="true"
                ref="bsTable"
                class="bsTable table table-hover table-striped table-borderless child-dom"
                @click="handleClick"
                @dblclick="doubleClickRow"
        ></table>
        <loading-acting :loadingState="loadTableData">
            <span class="text">正在努力地加载数据中，请稍后</span>
        </loading-acting>
        <empty-info :dataState="tableDataState"></empty-info>
    </div>
</template>
<style scoped lang="stylus">
    >>>.fixed-table-header>table
        position: relative
    >>>.fixed-table-pagination
        margin-top: 46px
    .table-normal
        position: relative
    .table
        color: #ffffff !important
</style>
<script>
    import {fetch, post} from "../../axios/http"
    import LoadingActing from '../../components/sub-common/loadingActing'
    import EmptyInfo from '../../components/sub-common/emptyInfo'

    export default {
        name: "bootsTable",
        components: {
            LoadingActing,
            EmptyInfo
        },
        props: {
            sidePageType: { // 表格分页类型，默认服务端分页，客户端类型：client
                type: String,
                default: 'server'
            },
            uniqueId: { // 表格按字段更新行数据，默认按照ID进行更新
                type: String,
                default: 'id'
            },
            isPage: { // 表格page是否从1开始，默认false
                type: Boolean,
                default: false
            },
            checkAll: { // 全选中
                type: Boolean,
                default: () => {
                    return false
                }
            },
            clientData: { // 客户端数据
                type: Object,
                default: () => {
                    return null
                }
            },
            afterLoad: { // 是否延时加载数据，默认false
                type: Boolean,
                default: () => {
                    return false
                }
            },
            pageList: { // 表格每页显示多少条数据列表
                type: Array,
                default: () => {
                    return ['10', '25', '50', '100', '1000']
                }
            },
            sortStable: { // 是否排序
                type: Boolean,
                default: function () {

                    return false

                }
            },
            sortName: {
                type: String,
                default: () => {
                    return ''
                }
            }, // 默认排序列
            sortOrder: { // 排序类型
                type: String,
                default: function () {
                    return 'desc'
                }
            },
            isData: {
                // 是否获取表格中所有的数据
                type: Boolean,
                default: function () {
                    return false
                }
            },
            disabled: {
                // 是否允许checkbox置灰
                type: Boolean,
                default: function () {
                    return false
                }
            },
            refresh: {
                type: Boolean,
                default: function () {
                    // 是否重新加载表格，默认false
                    return false
                }
            },
            searchName: String, // 搜索的字段名
            searchPlaceholder: {
                // 搜索框中的placeHolder设置
                type: String,
                default: function () {
                    return "搜索"
                }
            },
            rowsDoubleClick: {
                type: Boolean,
                default: function () {
                    // 表格行双击事件，true可双击，false无双击；默认false
                    return false
                }
            },
            ajaxData: {
                // 异步请求数据，key[url, method, params],method不传默认get请求
                type: Object,
                default: function () {
                    return {
                        method: "get",
                        params: {}
                    };
                }
            },
            height: {
                // 表格高度，不传默认500
                type: Number,
                default: function () {
                    return 500
                }
            },
            sequenceNumber: {
                // 是否显示序号，默认显示
                type: Boolean,
                default: function () {
                    return true
                }
            },
            checkBox: {
                // 是否显示单选框，默认不显示
                type: Boolean,
                default: function () {
                    return false
                }
            },
            showColumns: {
                // 是否显示内容下拉框，默认不显示
                type: Boolean,
                default: function () {
                    return false
                }
            },
            search: {
                // 是否显示搜索框，默认不显示
                type: Boolean,
                default: function () {
                    return false
                }
            },
            pageSize: {
                // 每页显示多少条数据，默认10条
                type: Number,
                default: function () {
                    return 10
                }
            },
            showRefresh: {
                // 是否显示刷新按钮，默认false不显示
                type: Boolean,
                default: function () {
                    return false
                }
            },
            clickToSelect: {
                // 是否允许点击整行选中，默认true，可以点击整行选中
                type: Boolean,
                default: function () {
                    return false
                }
            },
            singleSelect: {
                // 是否可以多选，默认false可以多选
                type: Boolean,
                default: function () {
                    return false
                }
            },
            pagination: {
                // 分页参数，不传默认为true
                type: Boolean,
                default: function () {
                    return true
                }
            },
            queryParamsFunction: {
                // 传到后台的参数集合
                type: Function
            },
            sortable: {
                // 排序，默认false
                type: Boolean,
                default: function () {
                    return false
                }
            },
            columns: {
                type: Array
            },
            pageNumber: {
                // 当前页面值， 不传默认为1
                type:Number,
                default: function() {
                    return 1
                }
            }
        },
        data() {
            return {
                staticOptions: {
                    locale: "zh-CN",
                    iconSize: "outline",
                    striped: true,
                    dataType: "json",
                    toggle: "bsTable",
                    sidePagination: "server",
                    classes: "table-striped table-borderless"
                },
                loadTableData: false,
                resultOptions: {},
                tableData: null,
                offsetResult: 0,
                tableDataState: false
            };
        },
        watch: {
            clientData: function (val) {

                const $this = this

                if (!val) return

                const { data, el } = val

                $this.loadTableData = true

                $this.tableDataState = data.total <= 0

                $(`.${el} .bsTable`).bootstrapTable('load', data)

            },
            refresh: function (val) {
                const $this = this;
                if (val) {
                    const ele = $this.$refs.bsTable;

                    if ($this.ajaxData.type && ($this.ajaxData.type === 'handle')) {

                        $(ele).bootstrapTable("refresh")

                    } else {

                        $(ele).bootstrapTable("refreshOptions", {pageNumber : $this.pageNumber})    // 执行刷新并为第一页

                    }

                    delete $this.ajaxData['type']

                }
            }
        },
        updated() {

            this.setScrollBar()

        },
        mounted() {

            const $this = this

            if (!$this.afterLoad) {

                $this.loadTable()

            } else {

                setTimeout(() => {

                    $this.loadTable()

                }, 0)

            }

            $this.setScrollBar()

        },
        methods: {
            /**
             *  服务端数据请求
             */
            serverRequest() {

                const $this = this
                const bsTable = $this.$refs.bsTable

                if (!$this.ajaxData.url) {
                    $this.tableDataState = true
                    $this.loadTableData = true
                    return
                }

                return function (params) {
                    // const tableEle = $this.$(bsTable)
                    if ($this.refresh) {

                        params.data.search = ""

                    }

                    const paramsSet = $this.paramsData(params)

                    const ajaxFun = $this.ajaxType(paramsSet)

                    $this.loadTableData = false

                    $this.tableDataState = false

                    $(bsTable).bootstrapTable("load", [])

                    ajaxFun.then(function (res) {

                        $this.$emit("responseData", res)

                        $this.loadTableData = true

                        if (res.resultCode === 200) {

                            const data = res.rows ? res : res.data

                            if (!data) {

                                $this.tableDataState = true

                                return

                            }

                            $this.tableData = data.rows

                            $this.$emit("total", data.total)

                            if ($this.isData) {

                                $this.$emit("data", data.rows)

                            }

                            if (data.total >= 0) {

                                $this.tableDataState = data.rows ? data.rows.length <= 0 : true

                            } else {

                                $this.tableDataState = data ? data.length <= 0 : true

                            }

                            params.success(data)

                            if ($this.checkAll) {

                                $(bsTable).bootstrapTable('checkAll')

                            }

                        } else {

                            $this.tableDataState = true

                            $(bsTable).bootstrapTable("load", [])

                        }

                    }).catch(() => {

                        $this.loadTableData = true

                        $this.tableDataState = true

                    })
                }

            },
            setScrollBar() {

                const $this = this

                $this.$healps.setScrollBar($('.table-normal .fixed-table-body'),{
                    whileScrolling:function(){

                        $('.fixed-table-header>table').css('left', this.mcs.left)

                    }
                })

                $this.$healps.setScrollBar($('.columns .dropdown-menu'))

            },
            /**
             * 表格数据加载
             */
            loadTable() {
                const $this = this;
                const bsTable = $this.$refs.bsTable
                const obj = $(bsTable)

                $this.ajaxData.params ? !$this.isPage ? $this.ajaxData.params.offset = 0 : '' : ''

                if ($this.sequenceNumber) {

                    const hssequn = $this.columns.some((item) => {

                        return item.field === 'INDEXID'

                    })

                    if(hssequn) {

                        $this.checkBox ? $this.columns.splice(1, 1) : $this.columns.splice(0, 1)

                    }

                    $this.columns.unshift({
                        field: "INDEXID",
                        title: "序号",
                        width: '2%',
                        sortable: $this.sortable,
                        formatter: function (value, row, index) {
                            const options = obj.bootstrapTable("getOptions"),
                                pageSize = options.pageSize, //通过表的#id 可以得到每页多少条
                                pageNumber = options.pageNumber; //通过表的#id 可以得到当前第几页

                            return pageSize * (pageNumber - 1) + index + 1; //返回每条的序号： 每页条数 * （当前页 - 1 ）+ 序号
                        }
                    })

                }

                if ($this.checkBox) {

                    const isCheck = $this.columns.some((item) => {

                        return item.checkbox

                    })

                    if (isCheck) {

                        $this.sequenceNumber ? $this.columns.splice(1, 1) : $this.columns.splice(0, 1)

                    }

                    $this.columns.unshift({

                        checkbox: true

                    })

                }

                const options = {
                    ajax: $this.sidePageType === 'server' ? $this.serverRequest() : '',
                    sidePagination: $this.sidePageType,
                    height: $this.height,
                    pagination: $this.pagination, // 设置为true会在底部显示分页条
                    paginationSuccessivelySize: 5,
                    paginationPagesBySide: 3,
                    singleSelect: $this.singleSelect, // 设置为true将禁止多选
                    clickToSelect: $this.clickToSelect, //设置为点击该行则整行都可以选择复选框
                    showRefresh: $this.showRefresh, //是否显示刷新按钮
                    // contentType : "application/x-www-form-urlencoded", //发送到服务器的数据编码类型
                    pageSize: $this.pageSize, // 如果设置了分页，每页数据条数
                    pageNumber: $this.pageNumber,
                    search: $this.search, // 是否显示搜索框
                    sortStable: $this.sortStable, // 是否排序
                    sortOrder: $this.sortOrder, // 排序
                    sortName: $this.sortName, // 默认排序列
                    showColumns: $this.showColumns, // 是否显示内容下拉框（选择显示的列）
                    columns: $this.columns,
                    pageList: $this.pageList,  //每页显示的条数
                    uniqueId: $this.uniqueId
                }

                $this.staticOptions.toggle = $(bsTable).data("id")

                const optionsAll = $.extend(true, $this.staticOptions, options)

                $this.resultOptions = optionsAll

                $(bsTable).bootstrapTable(optionsAll)

                $('.fixed-table-toolbar .search > input').attr('placeholder', $this.searchPlaceholder)
            },
            ajaxType(params) {
                const $this = this
                let ajaxFun = null

                if ($this.ajaxData.method === "post") {

                    ajaxFun = post($this.ajaxData.url, params)

                } else {

                    ajaxFun = fetch($this.ajaxData.url, params)

                }

                return ajaxFun;
            },
            paramsData(obj) {
                const $this = this

                let paramsObj = {}

                if ($this.pagination) {

                    let offset = $this.isPage ? (obj.data.offset / obj.data.limit) + 1 : obj.data.offset

                    const params = {

                        limit: obj.data.limit,

                        offset: offset

                    }

                    if ($this.sortStable) {

                        params.order = obj.data.order

                        params.sort = obj.data.sort

                    }

                    // 设置分页传参数据
                    paramsObj = $.extend(true, $this.ajaxData.params, params)

                } else {

                    paramsObj = $this.ajaxData.params

                }

                if ($this.search) {

                    // 如果设置了搜索，就添加搜索的值
                    paramsObj[$this.searchName] = obj.data.search

                }

                return paramsObj
            },
            /**
             * 表格双击事件
             * @param e
             * @returns {boolean}
             */
            doubleClickRow(e) {
                const $this = this

                if (!$this.rowsDoubleClick) {
                    return false
                }

                if ($(e.target).hasClass('btn') || $(e.target).parent().hasClass("btn")) {
                    return false
                }

                const tr = $(e.target).parent("tr")

                if (tr) {
                    const index = $(tr).data("index"),
                        rowData = $this.tableData[index]

                    $this.$emit("doubleClickRow", e.target, rowData)
                }
            },
            /**
             * 表格操作事件
             * @param e
             */
            handleClick(e) {
                const $this = this
                const self = $(e.target)
                let obj = null

                if ($this.checkBox) {
                    const selections = JSON.stringify(
                        $($this.$refs.bsTable).bootstrapTable("getSelections")
                    );
                    $this.$emit("getSelections", selections)
                }

                self.hasClass("btn") || self.hasClass("dcim") ? obj = self : obj = self.parent()

                if (obj.attr('href')) obj.removeAttr('href')

                if (!(obj.hasClass("btn") || obj.hasClass("dcim"))) return

                if ($this.tableData){

                    const row = $this.tableData[obj.data("index")]

                    $this.$emit("handleClick", obj, row)

                }else{

                    $this.$emit("handleClick", obj, obj.data("index"))

                }


                // if (obj.data("index") >= 0) {
                //     row = $this.tableData[obj.data("index")]
                // }
            }
        },
        beforeDestroy() {

            const $this = this;

            const ele = $this.$refs.bsTable;

            $(ele).bootstrapTable("destroy");


        },
    };
</script>
